package validators;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;


@ManagedBean(name = "emailValidator")
@SessionScoped
public class EmailValidator implements Validator {

	private String messageClass;

	private Boolean disabled;
	
	

	/**
	 * @param messageClass
	 *            the messageClass to set
	 */
	public void setMessageClass(String messageClass) {
		this.messageClass = messageClass;
	}

	/**
	 * @return the messageClass
	 */
	public String getMessageClass() {
		return messageClass;
	}

	@Override
	public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException {

		String email = (String) value;
		// Set the email pattern string
		Pattern p = Pattern.compile(".+@.+\\.[a-z]+");
		// Match the given string with the pattern
		Matcher m = p.matcher(email);
		// check whether match is found
		boolean matchFound = m.matches();
		if (matchFound) {
			this.setDisabled(true);
			context.addMessage(component.getClientId(), new FacesMessage("The email was sent successfully !"));
			setMessageClass("errorMessages");
			
		}
		else {
			this.setDisabled(false);
			context.addMessage(component.getClientId(), new FacesMessage("Email address is incorect !"));
			setMessageClass("info");
			
			
		}

	}

	public void setDisabled(Boolean disabled) {
		this.disabled = disabled;
	}

	public Boolean getDisabled() {
		return disabled;
	}

}

